package com.example.abe.diandi.base;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

import example.abe.com.framework.viewinject.ViewInjectUtils;

public abstract class BaseActivity extends AppCompatActivity {

    protected Handler uiHandler = new Handler();

    private GestureDetector mGestureDetector;

    private View root;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        root = getLayoutInflater().inflate(getLayoutID(), null);
        setContentView(root);
        ViewInjectUtils.inject(this);
        initData();
        initView();
    }

    abstract public int getLayoutID();

    abstract public void initData();

    abstract public void initView();

    protected void replaceFragment(View view, Fragment fragment) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(view.getId(), fragment);
        transaction.commit();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (mGestureDetector == null) {
            //初始化手势监听类
            mGestureDetector = new GestureDetector(this, onGestureListener);
        }
        mGestureDetector.onTouchEvent(ev);
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 侧滑(左->右)回调
     */
    public void onSideSlipEvent(){}

    private GestureDetector.OnGestureListener onGestureListener = new GestureDetector.OnGestureListener() {
        private boolean isLeftEdge;

        @Override
        public boolean onDown(MotionEvent e) {
            if (e.getRawX() < 20) {
                isLeftEdge = true;
            }else {
                isLeftEdge = false;
            }
            return false;
        }

        @Override
        public void onShowPress(MotionEvent e) {
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return false;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            return false;
        }

        @Override
        public void onLongPress(MotionEvent e) {
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            if (e1 != null && e2 != null && isLeftEdge) {
                float distanceX = e2.getRawX() - e1.getRawX();
                if (distanceX > 100) {
                    onSideSlipEvent();
                    return true;
                }
            }
            return false;
        }
    };
}
